package com.frontop.system.modules.sale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frontop.system.config.NacosConfig;
import com.frontop.system.modules.sale.model.SaleInfo;
import com.frontop.system.modules.sale.mapper.SaleInfoMapper;
import com.frontop.system.modules.sale.service.SaleInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frontop.system.modules.sale.vo.SaleInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 营销信息 服务实现类
 * </p>
 *
 * @author YangJia
 * @since 2022-04-24
 */
@Service
public class SaleInfoServiceImpl extends ServiceImpl<SaleInfoMapper, SaleInfo> implements SaleInfoService {
    @Autowired
    SaleInfoMapper saleInfoMapper;

    @Autowired
    NacosConfig nacosConfig;
    @Override
    public Page<SaleInfo> saleListPage(Page<SaleInfo> page, SaleInfoVO vo) {
        return saleInfoMapper.saleListPage(page,vo);
    }

    @Override
    public String upSaleHeadImage(MultipartFile multipartFile, Integer id) {
        //获取文件后缀
        String fileType = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));

        try {
            String uuid = String.valueOf(UUID.randomUUID());
            String uploadPath = nacosConfig.getUploadPath() + "sale_head_image/"+id+"-"+uuid+fileType;
            File file = new File(nacosConfig.getUploadPath() + "sale_head_image");
            if(!file.exists()){
                file.mkdirs();
            }
            multipartFile.transferTo(new File(uploadPath));

            //删除旧头像
            String loPath = saleInfoMapper.selectById(id).getHeadPath();
            if(StringUtils.isNotEmpty(loPath) && !loPath.equals("defult.gif")){
                File loFile = new File(nacosConfig.getUploadPath() + "sale_head_image/"+loPath);
                if (loFile.exists()) {
                    loFile.delete();
                }
            }
            SaleInfo saleInfo = new SaleInfo();
            saleInfo.setId(id);
            saleInfo.setHeadPath(id+"-"+uuid+fileType);
            saleInfoMapper.updateById(saleInfo);
            return id+"-"+uuid+fileType;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
